//
//  ChatViewController.m
//  Xmpp
//
//  Created by lanou3g on 16/1/29.
//  Copyright © 2016年 徐强. All rights reserved.
//

#import "ChatViewController.h"
#import "Manager.h"
@interface ChatViewController ()<XMPPStreamDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic , strong)UITableView *tableView;
@property (nonatomic ,strong)NSArray *messageArr;
///消息输入框
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[Manager shareManage].stream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, 375, 567) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    //一进来就刷新以前的消息
    [self loadMessage];
}
//退出聊天
- (IBAction)backChat:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//发送消息
- (IBAction)sendMessage:(id)sender {
    //初始化消息对象 文本（chat） to：好友的jid
//    XMPPMessage *message = [XMPPMessage message];
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.jid];
    
    [message addBody:self.textField.text];
    //发送消息
    [[Manager shareManage].stream sendElement:message];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messageArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *string = @"cell_ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    if (self.messageArr.count > 0 ) {
        
        XMPPMessageArchiving_Message_CoreDataObject *message = self.messageArr[indexPath.row];
        cell.textLabel.text = message.body;
        //查看消息是否发出
        if (message.isOutgoing) {
            cell.backgroundColor = [UIColor yellowColor];
        }else{
            cell.backgroundColor = [UIColor greenColor];
        }
    }
    
    return cell;
}
#pragma mark - 数据库中查找消息对象
- (void)loadMessage{
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //创建实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:[Manager shareManage].context];
    [fetchRequest setEntity:entity];
    //谓词 (根据自己的用户名与好友的用户名去coredata中搜索)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND bareJidStr == %@",[Manager shareManage].stream.myJID.bare,self.jid.bare];
    [fetchRequest setPredicate:predicate];
    //根据时间排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //执行查找
    NSArray *fetchedObjects = [[Manager shareManage].context executeFetchRequest:fetchRequest error:&error];
    //每次超过100条，删除第一条（防止内存变的太大造成崩溃）
    if (fetchedObjects.count > 100) {
        [fetchedObjects.mutableCopy delete:fetchedObjects[0]];
    }
    //每次数据库更新都赋值一次
    self.messageArr = fetchedObjects;
    //刷新表格
    [self.tableView reloadData];
    
    //判断聊天信息是否为零（为0就返回）
    if (self.messageArr.count < 1 ) {
        return;
    }
    //不为0就界面滑动到最后一行
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageArr.count-1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
    
}



#pragma mark - streamDelegate
//发送消息成功
- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message{
    NSLog(@"发送消息成功");
    [self loadMessage];
}
//接收到消息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    NSLog(@"接收好友消息");
    [self loadMessage];
}

//发送消息失败
- (void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error{
    NSLog(@"发送消息失败");
}



@end
